package com.ztesoft.report.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ztesoft.report.base.pojo.R;
import com.ztesoft.report.dao.ReportCategoryDao;
import com.ztesoft.report.dao.ReportDownloadDao;
import com.ztesoft.report.dao.ReportUploadDao;
import com.ztesoft.report.dao.UploadLogDao;
import com.ztesoft.report.entity.ReportCategory;
import com.ztesoft.report.entity.ReportUpload;
import com.ztesoft.report.entity.UploadLog;
import com.ztesoft.report.service.ReportDownloadService;
import com.ztesoft.report.utils.AESUtil;
import com.ztesoft.report.utils.ftp.SftpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 谭宏伟
 * @since 2018-06-13
 */
@Service
@Slf4j
@PropertySource(value = "classpath:backStageJob.properties")
public class ReportDownloadServiceImpl implements ReportDownloadService {
    @Autowired
    ReportUploadDao reportUploadDao;

    @Autowired
    UploadLogDao uploadLogDao;

    @Autowired
    ReportCategoryDao reportCategoryDao;

    @Autowired
    ReportDownloadDao reportDownloadDao;
    @Value("${com.ztesoft.downpath}")
    private String path;

    @Override
    public R queryPage( Map<String,Object> map) {
        //分页处理
        int current = (int) map.get("current");
        int size = (int) map.get("size");
        PageHelper.startPage(current, size);
        List<UploadLog> list = uploadLogDao.queryLogList(map);
        PageInfo<UploadLog> page  = new PageInfo(list);
        //由于已经改了查询逻辑 不在从服务器查询，这里全部注释
/*        //查询出要下载数据的服务器位置信息
        ReportUpload reportUpload = reportDownloadDao.queryUpload(map);
        String host = reportUpload.getHost();
        int port = Integer.parseInt(reportUpload.getPort());
        String username = reportUpload.getUsername();
        String password = AESUtil.decrypt(reportUpload.getPassword());
        String path = reportUpload.getPath();
        //返回前台的集合
        List<ReportDownload> webList = new ArrayList<>();
        //从服务器获取的日期格式
        String pattern = "EEE MMM dd HH:mm:ss zzz yyyy";
        //返回给前台日期格式
        String webpattern = "yyyy-MM-dd HH:mm:ss";
        int timeout = 2000;
        int aliveMax = 2000;
        //文件后缀以,分割 大小写不限
        String suffix ="xls,xlsx";
        SftpClient sftpClient = null;
        try {
            sftpClient = SftpClient.connect(host, port, username, password, timeout, aliveMax);
            List<Map<String,Object>> list =sftpClient.getSftpFile(path,suffix);
            log.info("查询到文件数量为："+list.size());
            for (Map<String,Object> sftp: list) {
                //新建一个实体来装每一条返回前台的数据
                ReportDownload reportDownload = new ReportDownload();
                //封装文件名
                reportDownload.setFilename(sftp.get("name").toString());
                Object obj = sftp.get("attr");
                if (obj instanceof SftpATTRS) {
                    //日期格式转换
                    String str=((SftpATTRS) obj).getMtimeString();
                    SimpleDateFormat df1 = new SimpleDateFormat(pattern, Locale.US);
                    Date date = df1.parse(str);
                    SimpleDateFormat df2 = new SimpleDateFormat(webpattern);
                    String webtime = df2.format(date);
                    reportDownload.setUploaddate(webtime);
                    //文件大小转换为kb
                    DecimalFormat df = new DecimalFormat(".00");
                    String filesize = df.format((((SftpATTRS) obj).getSize()+0.0)/1024);
                    reportDownload.setFilesize(filesize+"kb");
                    //封装文件主机地址
                    reportDownload.setHost(host);
                    //封装文件路径
                    reportDownload.setPath(path);
                    //封装数据源id
                    reportDownload.setFileid(reportUpload.getId());
                    //装入集合
                    webList.add(reportDownload);
                }
            }
            sftpClient.disconnect();
            //按日期排序
            Collections.sort(webList, new Comparator<ReportDownload>() {
                @Override
                public int compare(ReportDownload o1, ReportDownload o2) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date dt1 = format.parse(o1.getUploaddate());
                        Date dt2 = format.parse(o2.getUploaddate());
                        if (dt1.getTime() > dt2.getTime()) {
                            return -1;
                        } else if (dt1.getTime() < dt2.getTime()) {
                            return 1;
                        } else {
                            return 0;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });
            page = new PageInfo(webList);
        } catch (Exception e) {
            return new R().error("SFTP处理异常："+e.getMessage());
        }*/

        return new R().ok(page);
    }

    @Override
    public R downLoadFile(UploadLog uploadLog) {
        int timeout = 2000;
        int aliveMax = 2000;
        if (path == null && path =="") {
            return new R().error("下载路径未在配置文件里指定");
        }
        //查询出要下载数据的服务器位置信息
        ReportUpload reportUpload = reportDownloadDao.queryUpload(uploadLog.getReportUploadId());
        String password = AESUtil.decrypt(reportUpload.getPassword());
        try {
            SftpClient sftpClient  = SftpClient.connect(reportUpload.getHost(), Integer.parseInt(reportUpload.getPort()),
                    reportUpload.getUsername(), password, timeout, aliveMax);
            String filename = uploadLog.getReportName()+".xls";
            String uuid =UUID.randomUUID().toString();
            String src = uploadLog.getUploadPath()+"/"+filename;
            if (path.endsWith("/") || path.endsWith("\\")) {
                sftpClient.get(src,path+uuid+filename);
            } else {
                sftpClient.get(src,path+"/"+uuid+filename);
            }
            Map<String,Object> webValue = new HashMap<>();
            webValue.put("uuid",uuid);
            webValue.put("filename",filename);
            return new R().ok(webValue);
        } catch (Exception e) {
            e.printStackTrace();
            return new R().error("下载文件失败："+e.getMessage());
        }
    }

    @Override
    public List<ReportUpload> getServers() {
        Map<String,Object> map = new HashMap<>();
        return reportUploadDao.queryPages(map);
    }

    @Override
    public List<ReportCategory> getCategory() {
        return reportCategoryDao.getAll();
    }

    @Override
    public void downLoadLocal(HttpServletResponse response, HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        String filename = request.getParameter("filename");
        String id = request.getParameter("id");
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + java.net.URLEncoder.encode(filename, "utf-8"));
            String filePath = "";
            if (path.endsWith("/") || path.endsWith("\\")) {
                filePath = path + uuid +filename;
            } else {
                filePath = path + "/" + uuid + filename;
            }
            File file = new File(filePath);
            response.setContentLength(new Long(file.length()).intValue());
            InputStream inputStream = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.close();
            inputStream.close();
            file.delete();
            //更新下载次数
            UploadLog uploadLog = new UploadLog();
            uploadLog.setId(Integer.parseInt(id));
            uploadLog = uploadLogDao.selectById(uploadLog);
            uploadLog.setDownloadCount(uploadLog.getDownloadCount()+1);
            uploadLogDao.updateById(uploadLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
